import os
import shutil
from PyPDF2 import PdfMerger, PdfReader, PdfWriter


def find_and_copy_pdfs(source_folder, target_folder):
    pdf_files = []
    for root, dirs, files in os.walk(source_folder):
        for file in files:
            if file.endswith('.pdf'):
                full_path = os.path.join(root, file)
                shutil.copy(full_path, target_folder)
                pdf_files.append(os.path.join(target_folder, file))
    return pdf_files


def remove_first_and_last_page(pdf_path, output_path):
    reader = PdfReader(pdf_path)
    writer = PdfWriter()
    num_pages = len(reader.pages)

    # 添加所有页，除了第一页和最后一页
    for page_num in range(1, num_pages - 1):
        writer.add_page(reader.pages[page_num])

    with open(output_path, 'wb') as output_pdf:
        writer.write(output_pdf)


def merge_pdfs(pdf_files, output_file):
    merger = PdfMerger()
    for pdf in sorted(pdf_files):
        merger.append(pdf)
    merger.write(output_file)
    merger.close()


def main():
    source_folder = '/Users/e/Downloads/02.24基础考点讲解/01.24数据结构基础考点讲解'  # 源文件夹路径
    target_folder = '/Users/e/Downloads/res'  # 目标文件夹路径
    temp_folder = os.path.join(target_folder, 'temp')  # 临时文件夹路径，用于存储处理后的PDF文件
    output_file = os.path.join(target_folder, 'result.pdf')  # 合并后的PDF文件路径

    if not os.path.exists(target_folder):
        os.makedirs(target_folder)

    if not os.path.exists(temp_folder):
        os.makedirs(temp_folder)

    pdf_files = find_and_copy_pdfs(source_folder, target_folder)
    processed_pdfs = []

    for pdf in pdf_files:
        temp_pdf_path = os.path.join(temp_folder, os.path.basename(pdf))
        remove_first_and_last_page(pdf, temp_pdf_path)
        processed_pdfs.append(temp_pdf_path)

    merge_pdfs(processed_pdfs, output_file)

    # 清理临时文件夹
    for pdf in processed_pdfs:
        os.remove(pdf)
    os.rmdir(temp_folder)

    print(f'所有的PDF文件已合并到 {output_file}')


if __name__ == '__main__':
    main()
